package com.wunu.smartlock1;


import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import com.clj.fastble.data.BleDevice;
import com.google.gson.Gson;
import com.wunu.smartlock1.activity.AuthorizedLockActivity;
import com.wunu.smartlock1.activity.LockRecordActivity;
import com.wunu.smartlock1.activity.QrcodeActivity;
import com.wunu.smartlock1.activity.ScanListActivity;
import com.wunu.smartlock1.activity.TemporyLockActivity;
import com.wunu.smartlock1.activity.TemporyLockShowActivity;
import com.wunu.smartlock1.bluetooth.WunuBlueManager;
import com.wunu.smartlock1.bluetooth.command.OpenLockSetp2Command;
import com.wunu.smartlock1.bluetooth.command.OpenLockStep1Command;
import com.wunu.smartlock1.model.GonResult;
import com.wunu.smartlock1.model.GonUs;
import com.wunu.smartlock1.model.GonViews;
import com.wunu.smartlock1.net.NetComponent;
import com.wunu.smartlock1.net.api.LockEventApi;
import com.wunu.smartlock1.net.api.LockManageApi;
import com.wunu.smartlock1.net.response.ApiNormalResponse;
import com.wunu.smartlock1.net.response.ApiRegistResponse;
import com.wunu.smartlock1.net.response.ApiSimpleResponse;
import com.wunu.smartlock1.net.response.BaseCodeInfo;
import com.wunu.smartlock1.net.response.LockEvent;
import com.wunu.smartlock1.net.response.LockItem;
import com.wunu.smartlock1.util.BlueUtil;
import com.wunu.smartlock1.util.CommonUtil;
import com.wunu.smartlock1.xxtea.XXTEA;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import retrofit2.Call;

public class MainActivity extends AppCompatActivity implements OnClickListener{
    LockEventApi service = NetComponent.getRetrofit().create(LockEventApi.class);
    String toast;
    private ViewPager viewPager;
    private LinearLayout ll_item;//灰点所在的线性布局
    private ImageView blue_iv;//小蓝点
    int position;//当前界面数（从0开始）
    private int pointWidth;//小灰点的距离
    private List<View> contentList = new ArrayList<View>();

    private static final int HANDLE_HD_EVENT = 992;
    private static final int HANDLE_SCAN_DEVICES_EVENT = 154;
    private static final int HANDLE_PUSH_LOCK_RESULT = 100;
    private static final int HANDLE_CHANGE_ICON = 101;

    //弹框事件处理
    private static final int HANDLE_LOCK_DELETE = 201;
    private static final int HANDLE_LOCK_STOP = 202;

    //
    View inflate;
    Dialog dialog;
    Intent intent = new Intent();

    TextView cancelView;//取消
    TextView resetView;//重置秘钥
    TextView stopView;//停用蓝牙解锁
    TextView deleteView;//删除门锁
    private ProgressDialog pd;
    Context context = this;

    //全局收集item与相对应的view
    List<GonUs> gonUsList = new ArrayList<GonUs>();
    //全局图标控制
    RelativeLayout staticRelativeLayoutNoAway;
    RelativeLayout staticRelativeLayoutNo;
    RelativeLayout staticRelativeLayoutYes;
    //全局正在使用的页面
    View staticItem;
    int staticOpenId = 0;
    public int isPatch(String mac){
        if(BlueUtil.devices==null || BlueUtil.devices.size()<1||mac.length()<5) return -1;
        String n2 = mac.substring(mac.length() -5).replaceAll("\\W+","");
        String n1 = null;
        for(int i=0;i<BlueUtil.devices.size();i++){
            n1 = BlueUtil.devices.get(i).getMac().substring(BlueUtil.devices.get(i).getMac().length()-5).replaceAll("\\W+","");
            System.out.println("n1:"+BlueUtil.devices.get(i).getMac()+"\tn2:"+mac);
            if(n1.equalsIgnoreCase(n2))return i;
        }
        return -1;
    }
    public BleDevice getBleDevice(String mac){
        String n2 = mac.substring(mac.length() -5).replaceAll("\\W+","");
        String n1 = null;
        for(int i=0;i<BlueUtil.devices.size();i++){
            n1 = BlueUtil.devices.get(i).getMac().substring(BlueUtil.devices.get(i).getMac().length()-5).replaceAll("\\W+","");
            System.out.println("n1:"+n1+"\tn2:"+n2);
            if(n1.equalsIgnoreCase(n2))return BlueUtil.devices.get(i);
        }
        return null;
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLE_HD_EVENT:
                    pd.dismiss();
                    GonResult gr = (GonResult)msg.obj;
                    Map<String, Object> stringMap = gr.getMap();
                    View temp1 = gr.getTemp();
                    staticItem = gr.getTemp();
                    System.out.println("开锁返回结果: "+stringMap);
                    final boolean flag ;
                    if (stringMap.get("errMsg") != null || !"1".equals(stringMap.get("success").toString())) {
                        flag = false;
                        Toast.makeText(context, "开锁失败!", Toast.LENGTH_SHORT).show();
                    } else{
                        temp1.findViewById(R.id.onLockedIcon).setVisibility(View.VISIBLE);
                        temp1.findViewById(R.id.noneAway).setVisibility(View.GONE);
                        temp1.findViewById(R.id.lockedIcon).setVisibility(View.GONE);
                        flag = true;
                        Toast.makeText(context, "开锁成功", Toast.LENGTH_SHORT).show();
                    }
                    //上传开锁结果
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try{
                                LockEventApi service = NetComponent.getRetrofit().create(LockEventApi.class);
                                int event = flag?LockEvent.EVENT_SUCCESS:LockEvent.EVENT_FAILED;
                                System.out.println("event:"+event);
                                Call<ApiSimpleResponse> call = service.sendOpenLockResult(staticOpenId, flag?LockEvent.EVENT_SUCCESS:LockEvent.EVENT_FAILED);
                                ApiSimpleResponse resp = call.execute().body();
                                System.out.println(staticOpenId+" resp: "+resp);
                                // 发送消息，把服务器返回的本文弹出吐司显示
                                Message msg = handler.obtainMessage();
                                msg.what = HANDLE_PUSH_LOCK_RESULT;
                                msg.obj = resp.getData().getCode();
                                handler.sendMessage(msg);
                            } catch (Exception e) {
                                System.out.println("上传开锁结果异常:" + e);
                            }
                        }
                    }.start();
                break;
                case HANDLE_SCAN_DEVICES_EVENT:
                    System.out.println("obj->"+msg.getData());
                    if (msg == null || msg.obj == null || ((List<LockItem>)msg.obj).size() <1){
                        pd.dismiss();
                        Toast.makeText(MainActivity.this, "未获取到用户锁列表,跳转到蓝牙搜索界面", Toast.LENGTH_SHORT).show();
                        startActivity(intent.setClass(MainActivity.this, ScanListActivity.class));
                        break;
                    }

                    handleScanDevicesEvent((List<LockItem>)msg.obj);

                    //蓝牙匹配操作
                    new Thread(){
                        public void run(){
                            bloothMatch();
                        }
                    }.start();
                    break;
                case HANDLE_PUSH_LOCK_RESULT:
                    System.out.println("上传开锁结果 : "+msg);
                    if(200 == (int)msg.obj){
                        Toast.makeText(context, "上传开锁结果成功", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(context, "上传开锁结果失败!", Toast.LENGTH_SHORT).show();
                    }
                    try {
                        Thread.sleep(2000);
                    }catch (Exception e){}
                    //更新UI,可以重新开锁
                    staticItem.findViewById(R.id.onLockedIcon).setVisibility(View.GONE);
                    staticItem.findViewById(R.id.noneAway).setVisibility(View.GONE);
                    staticItem.findViewById(R.id.lockedIcon).setVisibility(View.VISIBLE);
                    break;
                case HANDLE_CHANGE_ICON:
                    List<GonViews> ls = (List<GonViews>)msg.obj;
                    System.out.println("扫描附件蓝牙符合条件的个数:"+ls.size());
                    for(int i=0;i<ls.size();i++) {
                        final View temp = ls.get(i).getTemp();
                        temp.findViewById(R.id.lockedIcon).setVisibility(View.VISIBLE);
                        temp.findViewById(R.id.noneAway).setVisibility(View.GONE);
                        temp.findViewById(R.id.onLockedIcon).setVisibility(View.GONE);

                        //点击事件
                        ImageView hitUnlock = temp.findViewById(R.id.hitUnlock);//解锁图标
                        final BleDevice thisDevice = BlueUtil.devices.get(ls.get(i).getIndex());
                        final int openId = ls.get(i).getOpenId();
                        hitUnlock.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                staticRelativeLayoutNoAway = temp.findViewById(R.id.noneAway);
                                staticRelativeLayoutNo = temp.findViewById(R.id.lockedIcon);
                                staticRelativeLayoutYes = temp.findViewById(R.id.onLockedIcon);
                                staticOpenId = openId;
                                pd= ProgressDialog.show(MainActivity.this, "请等待", "正在开锁");
                                //开线程加载数据
                                new Thread() {
                                    @Override
                                    public void run() {
                                        int baseCode = 0;
                                        LockManageApi service = NetComponent.getRetrofit().create(LockManageApi.class);
                                        Call<ApiNormalResponse<BaseCodeInfo>> call = service.getLockBaseCode(openId);
                                        try{
                                            ApiNormalResponse<BaseCodeInfo> resp = call.execute().body();
                                            baseCode = resp.getData().getData().getBaseCode();
                                        }catch (Exception e){System.out.println("获取basecode失败!"+e.getMessage());
                                        }

                                        System.out.println("---------------open lock step 1----------->blcmd begin basecode:"+baseCode+" openId: "+openId);
                                        int[] v = {0, (int)(Math.random() * 10000000)};
                                        int[] k = {0,0,0,baseCode};

                                        final OpenLockStep1Command o1cmd = new OpenLockStep1Command(XXTEA.encrypt(v,k));
                                        final WunuBlueManager manager = WunuBlueManager.Companion.getShared();
                                        final int finalBaseCode = baseCode;
                                        manager.execute(o1cmd, thisDevice, new Function1<Map<String, ? extends Object>, Unit>() {
                                            @Override
                                            public Unit invoke(Map<String, ?> stringMap) {
                                                if (stringMap.isEmpty()) {
                                                    return null;
                                                }
                                                if (stringMap.get("errMsg") != null) {
                                                    Message msg = handler.obtainMessage();
                                                    msg.what = HANDLE_HD_EVENT;
                                                    msg.obj = stringMap;
                                                    handler.sendMessage(msg);
                                                    return null;
                                                }
                                                int sn = stringMap.get("n") == null ? 0 : Integer.parseInt(stringMap.get("n").toString());
                                                int sA = CommonUtil.getPrePrime(finalBaseCode,sn);
                                                int sB = CommonUtil.getSufPrime(finalBaseCode,sn);
                                                int[] sv = {0, sB};
                                                int[] sk = {0,0,0, sA};
                                                System.out.println("---------------open lock step 2----------->blcmd begin");
                                                OpenLockSetp2Command o2cmd = new OpenLockSetp2Command(XXTEA.encrypt(sv,sk));
                                                manager.execute(o2cmd, thisDevice, new Function1<Map<String, ? extends Object>, Unit>() {
                                                    @Override
                                                    public Unit invoke(Map<String, ?> stringMap) {
                                                        if (stringMap.isEmpty()) {
                                                            return null;
                                                        }
                                                        Message msg = handler.obtainMessage();
                                                        msg.what = HANDLE_HD_EVENT;
                                                        //msg.obj = stringMap;
                                                        msg.obj = new GonResult((Map<String, Object>)stringMap,temp);
                                                        handler.sendMessage(msg);
                                                        return null;
                                                    }
                                                });
                                                return null;
                                            }
                                        });
                                    }
                                }.start();
                            }
                        });
                    }
                    break;
                case HANDLE_LOCK_DELETE:
                    ApiRegistResponse resp = (ApiRegistResponse)msg.obj;
                    if(resp == null || resp.getCode()!=0
                            || resp.getData()==null || resp.getData().getCode() != 200){
                          Toast.makeText(context, "删除门锁失败", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(context, "删除门锁成功!", Toast.LENGTH_SHORT).show();
                        startActivity(intent.setClass(MainActivity.this, MainActivity.class));
                    }
                    dialog.dismiss();
                    break;
                case HANDLE_LOCK_STOP:
                    ApiRegistResponse respStop = (ApiRegistResponse)msg.obj;
                    if(respStop == null || respStop.getCode()!=0
                            || respStop.getData()==null || respStop.getData().getCode() != 200){
                        Toast.makeText(context, "停用蓝牙解锁失败", Toast.LENGTH_SHORT).show();

                    }else{
                        Toast.makeText(context, "停用蓝牙解锁成功!", Toast.LENGTH_SHORT).show();
                        startActivity(intent.setClass(MainActivity.this, MainActivity.class));
                    }
                    dialog.dismiss();
                    break;
                default:break;

            }
        }
    };

    /**
     * 蓝牙匹配操作
     */
    public void bloothMatch(){
        while(!BlueUtil.scanState){
            System.out.println("蓝牙扫描状态 : " + BlueUtil.scanState);
            try{
                Thread.sleep(300);
            }catch (Exception e){}
        }
        System.out.println("蓝牙扫描状态结束 : " + BlueUtil.scanState);
        System.out.println("扫描到的蓝牙列表大小 : " + BlueUtil.devices.size());

        List<GonViews> tempList = new ArrayList<GonViews>();
        for(int i=0;i<gonUsList.size();i++){
            LockItem lockItem = gonUsList.get(i).getLockItem();
            View temp = gonUsList.get(i).getTemp();
            int index = isPatch(lockItem.getMac());
            if(-1 != index){
                tempList.add(new GonViews(index,lockItem.getId(),temp));
                System.out.println("第"+i+"个符合条件:"+lockItem);
            }
        }
        Message msg = handler.obtainMessage();
        msg.what = HANDLE_CHANGE_ICON;
        msg.obj = tempList;
        handler.sendMessage(msg);
    }
    private void handleScanDevicesEvent(List<LockItem> list) {
        System.out.println("list size : "+list.size());
        Toast.makeText(MainActivity.this,"正在搜索附近蓝牙",Toast.LENGTH_SHORT).show();
        //添加页面
        for (int i=0;i<list.size();i++){
            final LockItem lockItem = list.get(i);
            System.out.println("首页界面锁信息: "+lockItem);
            final View temp ;
            temp = LayoutInflater.from(context).inflate(R.layout.smartlock_lock_list_unlock, null);
            TextView name = temp.findViewById(R.id.lockNameTextView);
            name.setText(list.get(i).getName());
            TextView mac = temp.findViewById(R.id.lockMacTextView);
            mac.setText("蓝牙名称："+list.get(i).getName());

            //成员类型memberGroup 0.管理员，1.家庭成员，2.保姆，3.钟点工
            TextView membershow = temp.findViewById(R.id.membershow);
            membershow.setText(list.get(i).getMemberType());
            final int memnerType = list.get(i).getMemberGroup();
            final int lockId = list.get(i).getId();

            ImageView a_addButton = temp.findViewById(R.id.addButton);//添加新锁
            ImageView a_memberButton = temp.findViewById(R.id.memberButton);//家庭成员
            ImageView a_temporaryKeyButton = temp.findViewById(R.id.temporaryKeyButton);//临时秘钥
            ImageView a_authorizedButton = temp.findViewById(R.id.authorizedButton);//授权成员
            ImageView a_lockEventButton = temp.findViewById(R.id.lockEventButton);//开锁记录
            ImageView a_lockQRCodeButton = temp.findViewById(R.id.lockQRCodeButton);//锁二维码
            a_addButton.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    System.out.println("添加新锁");
                    Log.v("添加新锁", "list 1:" );
                    startActivity(intent.setClass(MainActivity.this, ScanListActivity.class));
                }
            });
            membershow.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.v("家庭成员", "list 1:" );
                    memberShow(memnerType,lockId);
                }
            });
            a_memberButton.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Log.v("家庭成员", "list 1:" );
                    memberShow(memnerType,lockId);
                }
            });
            a_temporaryKeyButton.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Log.v("临时秘钥", "list 1:" );
                    intent.putExtra("lockItem",new Gson().toJson(lockItem));
                    startActivity(intent.setClass(MainActivity.this, TemporyLockActivity.class));
                }
            });
            a_authorizedButton.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Log.v("授权成员", "list 1:" );
                    intent.putExtra("lockId",String.valueOf(lockItem.getId()));
                    startActivity(intent.setClass(MainActivity.this, AuthorizedLockActivity.class));
                }
            });
            a_lockEventButton.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Log.v("开锁记录", "lockId: "+lockItem.getId() );
                    intent.putExtra("lockId",String.valueOf(lockItem.getId()));
                    startActivity(intent.setClass(MainActivity.this, LockRecordActivity.class));
                }
            });
            a_lockQRCodeButton.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Log.v("锁二维码", "list 1:" );
                    startActivity(intent.setClass(MainActivity.this, QrcodeActivity.class));
                }
            });

            contentList.add(temp);
            gonUsList.add(new GonUs(lockItem,temp));
        }

        //将图片的引用转化为图片控件存在List的集合中
        for(int i=0;i<contentList.size();i++){
            //绘制小灰点儿，有几个界面就绘制几个
            ImageView points = new ImageView(context);
            points.setImageResource(R.drawable.grey_point);//通过shape文件绘制好灰点
            //给第一个以外的小灰点儿设置左边距，保证三个灰点水平居中
            LinearLayout.LayoutParams lllp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);//拿到灰点所处的线性布局一样的形状（一些距离属性）
            if(i>0)
                lllp.leftMargin = 30;//设置左外边距，像素
            points.setLayoutParams(lllp);//把设置好左外边距的形状设置给灰点
            ll_item.addView(points);//将灰点加入线性布局
        }
        //为了完成蓝点在界面滑动时的动画效果，必须获取到灰点的边距，通过动态的给蓝点设置边距来完成动画效果
        //由于在执行onCreate方法时，界面还没有绘制完成，无法获取pointWidth，设定小蓝点绘制完成的事件监听，当小蓝点绘制完成再获取
        blue_iv.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //获取小灰点圆心间的距离，第1个灰点和第二个灰点的距离
                if(contentList.size()>1)
                    pointWidth = ll_item.getChildAt(1).getLeft()-ll_item.getChildAt(0).getLeft();
            }
        });

        VPAdapter vpAdapter = new VPAdapter();//创建适配器
        viewPager.setAdapter(vpAdapter);//ViewPager加载适配器
        //为ViewPager设定监听器，界面是滑动时让蓝点也跟着动
        viewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            //当前选中第几个界面
            public void onPageSelected(int arg0) {
                position = arg0;
            }
            /**
             * 界面滑动时回调此方法
             * arg0:当前界面数
             * arg1:界面滑动过的百分数（0.0-1.0）
             * arg2:当前界面偏移的像素位置
             */
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                int width;//小蓝点当前滑动距离
                width = (int) (arg1*pointWidth+arg0*pointWidth);//1个界面就要一个小灰点的距离，再加上滑动过的百分比距离就是当前蓝点的位置
                RelativeLayout.LayoutParams rllp= (LayoutParams) blue_iv.getLayoutParams();//拿到蓝点所在布局的形状
                rllp.leftMargin=width;//设置蓝点的左外边距
                blue_iv.setLayoutParams(rllp);//将设置好的形状设置给蓝点
            }
            //状态改变时调用：arg0=0还没滑动,arg0=1正在滑动,arg0=2滑动完毕
            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });

        pd.dismiss();
        Toast.makeText(MainActivity.this, "加载页面成功!", Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//设置App不显示菜单，黑乎乎的不好看

        //注意这两句代码的顺序，上面一句写在下面一句后面会报错
        setContentView(R.layout.smartlock_activity_main);

        System.out.println("CommonUtil.dump： "+CommonUtil.dump);
        //begin 添加获取剪切板内容功能，如果剪切板上包含特殊字符[吾家智锁]和[#tempKey]，则直接向临时密钥页面跳转
        ClipboardManager clipboardManager=(ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
        if(CommonUtil.dump && clipboardManager!=null) {
            ClipData cd2 = clipboardManager.getPrimaryClip();
            if (cd2 != null && cd2.getItemCount() > 0) {
                String str2 = cd2.getItemAt(0).getText().toString();
                System.out.println("剪切板内容: " + str2);
                String regex = "(?<=门锁)(.*?)的一个临时密钥(.*?)，.*?=(.*?)#";
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(str2);
                if(matcher.find() && matcher.groupCount() == 3){
                    System.out.println(matcher.groupCount());
                    System.out.println("all: "+matcher.group(0));
                    System.out.println("name: "+matcher.group(1));
                    System.out.println("tempNum: "+matcher.group(2));
                    System.out.println("tempKey: "+matcher.group(3));
                    intent.putExtra("tempKey","tempKey");
                    startActivity(intent.setClass(MainActivity.this, TemporyLockShowActivity.class));
                    return;
                }else {
                    System.out.println("有剪切内容但是不匹配");
                }
            }else {
                System.out.println("剪切板ClipData为空");
            }
        }else {
            System.out.println("剪切板内容为空");
        }
        //end 添加获取剪切板内容功能

        gonUsList.clear();
        //构建一个下载进度条
        pd= ProgressDialog.show(MainActivity.this, "请等待", "正在扫描附近蓝牙设备…");

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        ll_item = (LinearLayout) findViewById(R.id.ll_item);
        blue_iv = (ImageView) findViewById(R.id.blue_iv);

        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN},1000);
            } else {
                System.out.println("蓝牙设备校验通过");
                new Thread(){
                    public void run(){
                        BlueUtil.startScan();
                    }
                }.start();

            }
        }

        pd.dismiss();
        //构建一个下载进度条
        pd= ProgressDialog.show(MainActivity.this, "请等待", "正在查询绑定的锁列表…");

        //开线程加载数据
        new Thread() {
            @Override
            public void run() {
                super.run();
                try{
                    LockManageApi service = NetComponent.getRetrofit().create(LockManageApi.class);
                    Call<ApiNormalResponse<List<LockItem>>> call = service.getLockList();
                    ApiNormalResponse<List<LockItem>> resp = call.execute().body();
                    System.out.println("resp: "+resp);
                    // 发送消息，把服务器返回的本文弹出吐司显示
                    Message msg = handler.obtainMessage();
                    msg.what = HANDLE_SCAN_DEVICES_EVENT;
                    msg.obj = resp.getData().getData();
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    System.out.println("获取用户锁列表异常:" + e);
                    pd.dismiss();
                }
            }
        }.start();
    }

    class VPAdapter extends PagerAdapter{
        //返回ViewPager中总页数
        @Override
        public int getCount() {
            return contentList.size();
        }
        //判断视图是否由对象生成
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }
        @Override
        /**
         * 返回将哪一个对象放在当前ViewPager中
         * container：每一页的父容器
         * position：当前页（从0开始）
         */
        public Object instantiateItem(ViewGroup container, int position) {
            //浪费资源，每次滑到新的页都会创建新的的ImageView，我们选择先把ImageView控件存在List集合中，再按需要获取
            View content = contentList.get(position);
            container.addView(content);
            return content;
        }
        @Override
        /**
         * 从ViewPager中移除View对象
         */
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }


    public void memberShow(int memberType,final int lockId){
        dialog = new Dialog(this,R.style.smartlock_ActionSheetDialogStyle);
        inflate = LayoutInflater.from(this).inflate(R.layout.smartlock_buttom_dialog, null);
        cancelView = inflate.findViewById(R.id.cancel);//取消弹框
        deleteView = inflate.findViewById(R.id.deletelock);//删除弹框

        resetView = inflate.findViewById(R.id.resetlock);//重置密钥弹框
        stopView = inflate.findViewById(R.id.stoplock);//停用蓝牙解锁弹框
        resetView.setOnClickListener(this);
        stopView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){
                    public void run(){
                        try{
                            LockManageApi service = NetComponent.getRetrofit().create(LockManageApi.class);
                            Call<ApiRegistResponse> call = service.deleteLock(lockId);
                            ApiRegistResponse resp = call.execute().body();
                            System.out.println("停用蓝牙解"+" resp: "+resp);
                            // 发送消息，把服务器返回的本文弹出吐司显示
                            Message msg = handler.obtainMessage();
                            msg.what = HANDLE_LOCK_STOP;
                            msg.obj = resp;
                            handler.sendMessage(msg);
                        } catch (Exception e) {
                            System.out.println("停用蓝牙解结果异常:" + e);
                        }
                    }
                }.start();
            }
        });

        if(memberType != 0) {
            resetView.setVisibility(View.GONE);
            stopView.setVisibility(View.GONE);
        }
        cancelView.setOnClickListener(this);
        deleteView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){
                    public void run(){
                        try{
                            LockManageApi service = NetComponent.getRetrofit().create(LockManageApi.class);
                            Call<ApiRegistResponse> call = service.deleteLock(lockId);
                            ApiRegistResponse resp = call.execute().body();
                            System.out.println("删除门锁"+" resp: "+resp);
                            // 发送消息，把服务器返回的本文弹出吐司显示
                            Message msg = handler.obtainMessage();
                            msg.what = HANDLE_LOCK_DELETE;
                            msg.obj = resp;
                            handler.sendMessage(msg);
                        } catch (Exception e) {
                            System.out.println("删除门锁结果异常:" + e);
                        }
                    }
                }.start();
            }
        });

        dialog.setContentView(inflate);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity( Gravity.BOTTOM);
        dialog.show();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id == R.id.cancel){
            dialog.dismiss();
        }else if(id == R.id.resetlock){
            Toast.makeText(this,"点击了重置秘钥按钮",Toast.LENGTH_SHORT).show();
        }else if(id == R.id.deletelock){
            Toast.makeText(this,"点击了删除门锁按钮",Toast.LENGTH_SHORT).show();
        }else if(id == R.id.stoplock){
            Toast.makeText(this,"点击了停用蓝牙解锁按钮",Toast.LENGTH_SHORT).show();
        }
    }
    /*
    * 拉取锁列表
    * */
    private void fetchLockList() {
        LockManageApi api = NetComponent.getRetrofit().create(LockManageApi.class);
        Call<ApiNormalResponse<List<LockItem>>> call = api.getLockList( );
        try {
            ApiNormalResponse<List<LockItem>> resp = call.execute().body();
            Handler handler = new Handler(){
                @Override
                public void handleMessage(Message msg){
                    List<LockItem> locks = (List<LockItem>)msg.obj;
                    System.out.println("锁列表" + locks);
                    // TODO: - 显示锁列表
                    
                }
            };
            Message msg = handler.obtainMessage();
            if(resp == null || resp.getData() == null)msg.obj = null;
            else msg.obj = resp.getData().getData();
            handler.sendMessage(msg);
        } catch (Exception e) {
            System.out.println("开锁异常" + e);
        }

    }
}
